package com.vf.cloud.paas.app.master.common.server.ueManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import com.vf.cloud.paas.app.master.api.scene.service.ISceneAction;
import com.vf.cloud.paas.app.master.common.server.ueManager.channel.UEManagerChannelInitializer;
import com.vf.cloud.paas.common.service.IRedis;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.WriteBufferWaterMark;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class UEManagerServer {

	@Autowired
	private IRedis redisImpl;
	@Autowired
	private ISceneAction sceneActionImpl;
	
	@Value("${master.ue.port}")
	private int uePort;

	private EventLoopGroup boss;
	private EventLoopGroup work;
	private Channel channel;

	@Async
	public void run() {
		try {
			ServerBootstrap bootstrap = new ServerBootstrap();
			boss = new NioEventLoopGroup();
			work = new NioEventLoopGroup();

			log.info(">>>正在启动 --> UEManagerServer:" + uePort);
			bootstrap.group(boss, work);
			bootstrap.channel(NioServerSocketChannel.class);
			bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(512 * 1024, 1024 * 1024));
			bootstrap.childHandler(new UEManagerChannelInitializer(redisImpl,sceneActionImpl));
			channel = bootstrap.bind(uePort).sync().channel();
			log.info(String.format(">>> UEManagerServer listening on *:%s." ,uePort));

			if (channel != null && channel.closeFuture() != null) {
				channel.closeFuture().sync();
			}
		} catch (Exception e) {
		} finally {
			work.shutdownGracefully();
			boss.shutdownGracefully();
			log.info(">>>已关闭 --> UEManagerServer:" + uePort);
		}
	}

	public void destroy() {
		if (channel != null) {
			channel.close();
		}
		work.shutdownGracefully();
		boss.shutdownGracefully();
	}

}
